<?php
namespace App\Http\Controllers;

use DB;
use Session;
use Validator;
use Request;
use Laravel\Lumen\Routing\Controller;

class DataController extends BaseController
{	
    public function getWeek()
    {   
        $param = Request::all();
        $weekStartArr = Config('ptime.week_start_arr');
        $date = $param['date'];
        $lastMonday = date('Y-m-d',strtotime('last monday'));
        $weekNow = array_search($lastMonday, $weekStartArr);
        $weekNum = count($weekStartArr);
        $startDate = $weekStartArr[1];
        $endDate = date('Y-m-d',strtotime($weekStartArr[$weekNum].'+7 day'));
        if($date >= $startDate && $date <=$endDate){
            $result = [
                'week_now'   => $weekNow,
                'week_count' => $weekNum,
                'start_date' => $startDate,
                'end_date'   => $endDate
            ];
            return $this->jsonResponse(false,$result);
        }
        return $this->jsonResponse(false,[],'当前日期不在教学周内');
    }
	/**
     * @api {get} /table table
     * @apiVersion 0.2.0
     * @apiName table
     * @apiGroup data_flow
     * @apiPermission app
     *
     * @apiDescription 课表数据流
     *
     * @apiParam {String} token *用户token.
     *
     * @apiSuccess {Boolean} error 是否错误.
     * @apiSuccess {Object} result 结果.
     * @apiSuccess {String} result.title 标题
     * @apiSuccess {String} message 提示消息.
     *
     * @apiError paramError 参数错误.
     * @apiSampleRequest http://timepicker.cn:92/api/data/table
     */ 
	public function table()
	{   
        $userId = Session::get('user_id');
        $weekStartArr = Config('ptime.week_start_arr');
        //教学周
        $schoolWeekArr = array_keys($weekStartArr);
        //当前周周一
        $lastMonday = date('Y-m-d',strtotime('monday'));
        //获取当前周
        $tempWeekNow = array_search($lastMonday, $weekStartArr);
        $weekInput = isset($param['week']) ? $param['week'] : $tempWeekNow;
        $result['table_week'] = $weekInput;
        //获取选中周数的周一
        $monday = $weekStartArr[$weekInput];
        //获取选中周数的周日
        $sunday = date('Y-m-d',strtotime($monday.'next sunday'));
        $startTime = strtotime($monday);
        $endTime = strtotime($sunday);
        //当前周所有日期
        $dateArr = [];
        while($startTime <= $endTime){
            $dateArr[] = date('m-d',$startTime);
            $startTime = strtotime("+1 day",$startTime);
        }
        $result['school_week_all'] = $schoolWeekArr;
        $result['school_week_now'] = $tempWeekNow;
        $result['week_day'] = $dateArr;
        $result['date'] = date('m-d');
        $result['school_year'] = (date('Y')-1).'-'.date('Y');
        $result['term'] = date('m') <=8 ? 2 : 1;
        //学生课表
        $weekDay = ['1','2','3','4','5','6','7'];
        $tableDetail = DB::table('ed_record')
                        ->join('ed_user_record','ed_user_record.record_id','=','ed_record.id')
                        ->select('ed_record.*')
                        ->where('ed_user_record.user_id','=',$userId)
                        ->orderBy('ed_record.week_n','ASC')
                        ->orderBy('ed_record.class_n','ASC')
                        ->get();
        if(empty($tableDetail)){
            $tableDetailYan = DB::table('ed_record_yan')
                            ->join('ed_user_record_yan','ed_user_record_yan.record_id','=','ed_record_yan.id')
                            ->select('ed_record_yan.*')
                            ->where('ed_user_record_yan.user_id','=',$userId)
                            ->orderBy('ed_record_yan.week_n','ASC')
                            ->orderBy('ed_record_yan.class_n','ASC')
                            ->get();
            $tableData = [];
            //按星期排课
            foreach ($tableDetailYan as $key => $value) {
                $tableData[$value->week_n ][] = [
                    'id'                => $value->id,
                    'class_name'        => $value->class_name,
                    'addr'              => $value->addr,
                    'academy'           => $value->academy,
                    'subject_num'       => $value->subject_num,
                    'subject_name'      => $value->subject_name,
                    'teacher_name'      => $value->teacher_name,
                    'description'       => $value->description,                 
                    'week_start'        => $value->week_start,
                    'week_end'          => $value->week_end,
                    'week_n'            => $value->week_n,
                    'class_n'           => $value->class_n,
                    'class_p'           => $value->class_p,
                    'credit'            => $value->credit,
                    'is_degree'         => $value->is_degree,
                ]; 
            }
        }else{
            $tableData = [];
            //按节次排课
            foreach ($tableDetail as $key => $value) {
                $tableData[$value->week_n][] = [
                    'id'                => $value->id,
                    'subject_name'      => $value->subject_name,
                    'teacher_name'      => $value->teacher_name,
                    'addr'              => $value->addr,
                    'week_n'            => $value->week_n,
                    'week_start'        => $value->week_start,
                    'week_end'          => $value->week_end,
                    'class_n'           => $value->class_n,
                    'others'            => $value->others,
                ];
            }
        }                                
        foreach ($weekDay as $week_n) {
            $finalData[$week_n] = isset($tableData[$week_n]) ? $tableData[$week_n]:[];
        }
		return $this->jsonResponse(false,$finalData);
	}
}